package com.westar.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.jndi.toolkit.url.Uri;
import com.westar.base.cons.Constant;
import com.westar.base.exceptions.LoginException;
import com.westar.base.exceptions.SelfHttpException;
import com.westar.base.model.UserInfo;
import com.westar.base.pojo.UserAuth;
import com.westar.core.conf.SysConst;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import static com.westar.base.enums.HTTPResultEnum.*;

public class TokenUtil {


    private static Logger logger = LoggerFactory.getLogger( TokenUtil.class);

    private static Map<String, UserAuth> tokenTouserMap= new HashMap<String,UserAuth>(20);
    private static Map<String,String> userTokenMap= new HashMap<String,String>(20);

    static  Map<String,String> models = new HashMap<>();

    static  Map<String,String> models_new = new HashMap<>();

    static {
        models.put(Constant.MODEL_OAUTHUI,"http://"+SysConst.DOMAIN+"/oauthui/portal?pageType=1");
        models.put(Constant.MODEL_THINGSUI,"http://"+SysConst.DOMAIN+"/thingsui/portal");
        models.put(Constant.MODEL_DOTHINGSUI,"http://"+SysConst.DOMAIN+"/dothingsui/portal");

        //综合受办平台（新）
        models_new.put(Constant.MODEL_DOTHINGSUI_NEW,"http://59.225.201.162:8086/work_table/");

    }


    /**
     * 验证tooken是否有效
     * @param token token标识
     * @return
     */
    public static boolean checkToken(String token,String model){
        //根据token获取用户信息
        UserAuth userAuth = tokenTouserMap.get(token);
        //未获取到用户数据，返回false
        if(null == userAuth){
            return false;
        }
        //用户过期时间
        Date expressDate = userAuth.getExpressDate();
        //当前时间
        Date nowDate = new Date();
        //时间是否有效判断
        if(nowDate.before(expressDate)){
            //TOODO checkInfo
            //网络请求校验
            String  url = models.get(model);
            try {
                Map<String,String> result = WestarHttpUtil.postMethodForAll(url,userAuth.getLoginCookie().get(model),null);
                String code = result.get(CODE.toString());
                if(code.equals("200")){
                    return true;
                }else{
                    return false;
                }
            } catch (IOException e) {
                logger.error("验证session有效性！");
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 通过用户账号获取标识
     * @param account 账号
     * @return
     * @throws IOException
     * @throws SelfHttpException
     */
    public static String getTokenByAccount(String account) throws IOException, SelfHttpException {
        //通过账号获取token标识
        String token = userTokenMap.get(account);
        //唯一标识不存在
        if(null == token){
            return null;
        }
        //根据token获取用户信息
        UserAuth userAuth = tokenTouserMap.get(token);
        //没有查询到用户信息
        if(null == userAuth){
            return null;
        }
        //用户过期时间
        Date expressDate = userAuth.getExpressDate();
        //当前时间
        Date nowDate = new Date();
        //时间是否有效，有效则返回token
        if(nowDate.before(expressDate)){
            return token;
        }else{
            //根据用户信息重新更新token
            token = TokenUtil.updateUserToken(userAuth,token);
            return token;
        }
    }

    /**
     * 根据token获取用户信息
     * @param token token标识
     * @return
     */
    public static UserInfo getSessionUser(String token){
        //根据token获取用户信息
        UserAuth userAuth = tokenTouserMap.get(token);
        //取得用户信息
        UserInfo userInfo = userAuth.getUserInfo();
        return userInfo;
    }

    /**
     * 更新用户的有效期
     * @param token 身份认证
     * @param userInfo 当前操作员
     */
    public static void updateSessionUser(String token,UserInfo userInfo){

        UserAuth userAuth = tokenTouserMap.get(token);
        //当前时间
        String nowDateTime = DateTimeUtil.getNowDateStr( DateTimeUtil.yyyy_MM_dd_HH_mm_ss );
        String expressDateStr =  DateTimeUtil.addDate(nowDateTime,DateTimeUtil.yyyy_MM_dd_HH_mm_ss, Calendar.HOUR,24);
        //失效时间
        Date expressDate = DateTimeUtil.parseDate(expressDateStr,DateTimeUtil.yyyy_MM_dd_HH_mm_ss  );

        userAuth.setExpressDate(expressDate);
        userAuth.setUserInfo(userInfo);

        tokenTouserMap.put(token ,userAuth );

    }

    /**
     * 根据token获取浏览器的cookie缓存
     * @param token token标识initToken
     * @return
     * @throws IOException
     * @throws SelfHttpException
     */
    public static String getCookie(String token,String model) throws IOException, SelfHttpException {
        UserAuth userAuth = tokenTouserMap.get(token);
        if(null != userAuth){
            //当前时间
            String nowDateTime = DateTimeUtil.getNowDateStr( DateTimeUtil.yyyy_MM_dd_HH_mm_ss );
            String expressDateStr =  DateTimeUtil.addDate(nowDateTime,DateTimeUtil.yyyy_MM_dd_HH_mm_ss, Calendar.HOUR,24);
            //失效时间
            Date expressDate = DateTimeUtil.parseDate(expressDateStr,DateTimeUtil.yyyy_MM_dd_HH_mm_ss  );
            //验证token是否失效
            boolean tokenEffect = checkToken(token,model);
            if(!tokenEffect){//token失效
                //重新设定token
                userAuth.setExpressDate(expressDate);
                token = TokenUtil.getUserToken(userAuth);

                userAuth = tokenTouserMap.get(token);
            }
            return userAuth.getLoginCookie().get(model);
        }else{
            return null;
        }

    }

    /**
     * 用户登录
     * @param userAuth
     * @return
     * @throws IOException
     * @throws SelfHttpException
     */
    private static String getUserToken(UserAuth userAuth) throws IOException, SelfHttpException {
        //账号
        String account = userAuth.getUserInfo().getAccount();
        //密码
        String password = userAuth.getUserInfo().getPasswd();

        //登陆界面获取，需要提交登陆信息的方法
        String authorizeMethod = TokenUtil.getAuthorizePage(null);
        //取得登录的cookie
        Map<String,String> resultMap = TokenUtil.getLoginCookie(authorizeMethod,account,password);

        userAuth.setLoginCookie(resultMap);

        //用户在中间件的标识
        String token = UUIDGenerator.getUUID();
        //缓存 标识---人员信息
        userTokenMap.put(account,token);
        tokenTouserMap.put(token ,userAuth );
        return token;
    }



    /**
     * 更新失效的token
     * @param userAuth 用户信息
     * @param token 已有的token
     * @return
     * @throws IOException
     * @throws SelfHttpException
     */
    private static String updateUserToken(UserAuth userAuth,String token) throws IOException, SelfHttpException {
        //账号
        String account = userAuth.getUserInfo().getAccount();
        //密码
        String password = userAuth.getUserInfo().getPasswd();

        //登陆界面获取，需要提交登陆信息的方法
        String authorizeMethod = TokenUtil.getAuthorizePage(null);
        //取得登录的cookie
        Map<String,String>  resultMap = TokenUtil.getLoginCookie(authorizeMethod,account,password);
        userAuth.setLoginCookie(resultMap);

        //缓存 标识---人员信息
        userTokenMap.put(account,token);
        tokenTouserMap.put(token ,userAuth );
        return token;
    }
    /**
     * 获取登录人员的token
     * @param account
     * @return
     */
    public static String initToken(String account,String password,String model) throws IOException, SelfHttpException {
        //根据账号获取token
        String token = userTokenMap.get(account);
        //当前时间
        String nowDateTime = DateTimeUtil.getNowDateStr( DateTimeUtil.yyyy_MM_dd_HH_mm_ss);
        String expressDateStr =  DateTimeUtil.addDate(nowDateTime,DateTimeUtil.yyyy_MM_dd_HH_mm_ss, Calendar.HOUR,24);
        //失效时间
        Date expressDate = DateTimeUtil.parseDate(expressDateStr,DateTimeUtil.yyyy_MM_dd_HH_mm_ss  );

        if(null == token){
            //没有token,则登录
            UserAuth userAuth = new UserAuth();
            userAuth.setExpressDate(expressDate);

            UserInfo userInfo = new UserInfo();
            userInfo.setPasswd(password);
            userInfo.setAccount(account);

            userAuth.setUserInfo(userInfo);

            token = TokenUtil.getUserToken(userAuth);
        }else{
            //TODO 验证token是否失效
            boolean tokenEffect = checkToken(token,model);

            if(!tokenEffect){
                //token失效,需要重新登录
                UserAuth userAuth = new UserAuth();
                userAuth.setExpressDate(expressDate);

                UserInfo userInfo = new UserInfo();
                userInfo.setPasswd(password);
                userInfo.setAccount(account);

                userAuth.setUserInfo(userInfo);

                token = TokenUtil.updateUserToken(userAuth,token);
            }else{
                //token有效,获取用户信息
                UserAuth userAuth = tokenTouserMap.get(token);
                //取得用户的密码
                String passwordCache = userAuth.getUserInfo().getPasswd();
                //密码不同需要重新登录
                if(!passwordCache.equals(password)){
                    userAuth = new UserAuth();
                    userAuth.setExpressDate(expressDate);

                    UserInfo userInfo = new UserInfo();
                    userInfo.setPasswd(password);
                    userInfo.setAccount(account);

                    userAuth.setUserInfo(userInfo);

                    token = TokenUtil.updateUserToken(userAuth,token);
                }
            }
        }
        return token;
    }



    /**
     * 获取登录后的cookie
     * @param authorizeMethod 需要提交登陆信息的方法 https://59.225.209.96/auth/oauth/authorize?response_type=code&client_id=OAuthPlatform
     *                        &redirect_uri=http%3A%2F%2F59.225.209.242%2Foauthui%2Fmain%2Flogin&scope=user_info&state=59HM0"
     * @param username 当前操作人员的账号
     * @param password 当前操作人员的密码
     * @return
     */
    private static Map<String,String> getLoginCookie(String authorizeMethod,String username, String password)
            throws SelfHttpException, IOException {

        username = RSAUtils.encrypt(username,RSAUtils.publicKey);
        password = RSAUtils.encrypt(password,RSAUtils.publicKey);

        HttpClient httpclient = new HttpClient();
        // 设置浏览器相同的cookie接收策略
        httpclient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        HttpMethod method = new PostMethod();

        //设置支持https访问
        Protocol myhttpsV2 = new Protocol("https",
                new MySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttpsV2);

        method.setPath(authorizeMethod);

        int statusCode = httpclient.executeMethod(method);
        if(statusCode != 200){
            method.releaseConnection();
            throw new SelfHttpException(SelfHttpException.PAGE_NOT_FOUND,"中间件不能访问网络，请求不成功!" , "");
        }
        //着陆页cookie
        String cookie2 = TokenUtil.getCookie(method);

        String loginPageV2 =  method.getResponseBodyAsString();
        method.releaseConnection();

        //开始验证登录[异步提交表单]
        String loginResult = TokenUtil.loginAction(loginPageV2,username,password,"utf-8",cookie2);
        //获取登录结果
        JSONObject res = JSONObject.parseObject(loginResult );
        if(res.getBoolean("ok"  )){

            //登录后处理[国家登录平台的cookie]
            Map<String,String>  resultMap = TokenUtil.mainLogin(authorizeMethod,cookie2,username,password);

            //http://59.225.209.96/thingsui/portal



            return resultMap;
        }else{
            throw new SelfHttpException(SelfHttpException.LOGIN_ERROR,"%s",res.getString("msg") );
        }
    }

//    private static String getFinalCookie(String cookie3, String cookie4) throws IOException, SelfHttpException {
//        //用于跳转的url
//        String directurl = "http://"+SysConst.DOMAIN+"/thingsui/portal";
//        Map<String,String> result = WestarHttpUtil.getForAllMethod(directurl,cookie4,null);
////        Iterator<Map.Entry<String, String>> iterator = result.entrySet().iterator();
////        while (iterator.hasNext()){
////            Map.Entry<String, String> entry = iterator.next();
////            System.out.println("/thingsui/portal--> getKey = " + entry.getKey());
////            System.out.println("/thingsui/portal--> getValue =" + entry.getValue());
////        }
//        String cookie4Final = result.get(COOKIE.toString());
//        //http://59.225.209.96/thingsui/oauth2/login
//        String location = result.get(LOCATION.toString());
//        result = WestarHttpUtil.getForAllMethod(location,cookie4Final,null);
////        iterator = result.entrySet().iterator();
////        while (iterator.hasNext()){
////            Map.Entry<String, String> entry = iterator.next();
////            System.out.println("/oauth2/login--> getKey = " + entry.getKey());
////            System.out.println("/oauth2/login--> getValue =" + entry.getValue());
////        }
//
//
////        System.out.println("cookie3 = " + cookie3);
////        System.out.println("cookie4 = " + cookie4);
//
//        String loginPage = result.get(RESPONEBODY.toString());
//        //页面Doc化
//        Document doc = Jsoup.parse(loginPage);
//        //页面表单元素
//        Elements eleForm = doc.select("form");
//        //页面需要执行的请求
//        String submitForm = eleForm.attr( "action");
//
//        result = WestarHttpUtil.postMethodForAll(submitForm, cookie3+";"+cookie4Final, null);
//
////        iterator = result.entrySet().iterator();
////        while (iterator.hasNext()){
////            Map.Entry<String, String> entry = iterator.next();
////            System.out.println("checkNationalLogin--> getKey = " + entry.getKey());
////            System.out.println("checkNationalLogin--> getValue =" + entry.getValue());
////        }
//
//        location = result.get(LOCATION.toString());
//        result = WestarHttpUtil.getForAllMethod(location,cookie4Final,null);
////        iterator = result.entrySet().iterator();
////        while (iterator.hasNext()){
////            Map.Entry<String, String> entry = iterator.next();
////            System.out.println("manaui/main/login--> getKey = " + entry.getKey());
////            System.out.println("manaui/main/login--> getValue =" + entry.getValue());
////        }
//
////        String url = "http://59.225.209.96/thingsui//portal";
////        result = WestarHttpUtil.getForAllMethod(url,cookie4,null);
////        iterator = result.entrySet().iterator();
////        while (iterator.hasNext()){
////            Map.Entry<String, String> entry = iterator.next();
////            System.out.println("thingsui/portal--> getKey = " + entry.getKey());
////            System.out.println("thingsui/portal--> getValue =" + entry.getValue());
////        }
//        return cookie4Final;
//    }

    private static String getFinalCookie(String cookie3, String cookie4,String directurl) throws IOException, SelfHttpException {
        //用于跳转的url
        Map<String,String> result = WestarHttpUtil.getForAllMethod(directurl,cookie4,null);
//        Iterator<Map.Entry<String, String>> iterator = result.entrySet().iterator();
//        while (iterator.hasNext()){
//            Map.Entry<String, String> entry = iterator.next();
//            System.out.println("/thingsui/portal--> getKey = " + entry.getKey());
//            System.out.println("/thingsui/portal--> getValue =" + entry.getValue());
//        }
        String cookie4Final = result.get(COOKIE.toString());
        //http://59.225.209.96/thingsui/oauth2/login
        String location = result.get(LOCATION.toString());
        result = WestarHttpUtil.getForAllMethod(location,cookie4Final,null);
//        iterator = result.entrySet().iterator();
//        while (iterator.hasNext()){
//            Map.Entry<String, String> entry = iterator.next();
//            System.out.println("/oauth2/login--> getKey = " + entry.getKey());
//            System.out.println("/oauth2/login--> getValue =" + entry.getValue());
//        }


//        System.out.println("cookie3 = " + cookie3);
//        System.out.println("cookie4 = " + cookie4);

        String loginPage = result.get(RESPONEBODY.toString());
        //页面Doc化
        Document doc = Jsoup.parse(loginPage);
        //页面表单元素
        Elements eleForm = doc.select("form");
        //页面需要执行的请求
        String submitForm = eleForm.attr( "action");

        result = WestarHttpUtil.postMethodForAll(submitForm, cookie3+";"+cookie4Final, null);

//        iterator = result.entrySet().iterator();
//        while (iterator.hasNext()){
//            Map.Entry<String, String> entry = iterator.next();
//            System.out.println("checkNationalLogin--> getKey = " + entry.getKey());
//            System.out.println("checkNationalLogin--> getValue =" + entry.getValue());
//        }

        location = result.get(LOCATION.toString());
        result = WestarHttpUtil.getForAllMethod(location,cookie4Final,null);
//        iterator = result.entrySet().iterator();
//        while (iterator.hasNext()){
//            Map.Entry<String, String> entry = iterator.next();
//            System.out.println("manaui/main/login--> getKey = " + entry.getKey());
//            System.out.println("manaui/main/login--> getValue =" + entry.getValue());
//        }

        String tempCookie = result.get(COOKIE.toString());
        if(StringUtils.isNotEmpty(tempCookie) && tempCookie.toLowerCase().indexOf("session")>=0){
            cookie4Final = result.get(COOKIE.toString());
        }


//        String url = "http://59.225.209.96/thingsui//portal";
//        result = WestarHttpUtil.getForAllMethod(directurl,cookie4Final,null);
//        iterator = result.entrySet().iterator();
//        while (iterator.hasNext()){
//            Map.Entry<String, String> entry = iterator.next();
//            System.out.println("thingsui/portal--> getKey = " + entry.getKey());
//            System.out.println("thingsui/portal--> getValue =" + entry.getValue());
//        }
        System.out.println("cookie4Final =" + cookie4Final);
        return cookie4Final;
    }

    /**
     * 登录后的cookie标识获取
     * @param authorizeMethod 链接跳转地址
     * @param cookie2
     * @return
     * @throws LoginException
     * @throws IOException
     */
    private static  Map<String,String>  mainLogin(String authorizeMethod,String cookie2,String account,String passwd)
            throws IOException, SelfHttpException {
        //location.replace(location.href);
        String cookie3 = null;

        //获取需要跳转的地址
        Map<String,String> result = WestarHttpUtil.getForAllMethod(authorizeMethod,cookie2,null);
        String code = result.get(CODE.toString());

        if("302".equals(code)){
            //http://59.225.209.96/manaui/main/login?code=Y8d8Rc&state=8X0J5
            String location = result.get(LOCATION.toString());
            cookie3 = result.get(COOKIE.toString()) ;
            result = WestarHttpUtil.getForAllMethod(location,cookie3,null);
        }else{
            throw new SelfHttpException( SelfHttpException.PAGE_RE_LOGIN,"%s","登录请求地址变动，需要重新登录！" );
        }


        String cookie4 = null;
        code = result.get(CODE.toString());
//        System.out.println(" code = " + code);
        if("302".equals(code)){
            String location = result.get(LOCATION.toString());
            result = WestarHttpUtil.getForAllMethod(location,cookie3,null);
            cookie4 = result.get(COOKIE.toString());
        }else{
            throw new SelfHttpException( SelfHttpException.PAGE_RE_LOGIN,"%s","登录请求地址变动，需要重新登录！" );
        }




        Map<String,String> resultMap = new HashMap<>();
        Iterator<Map.Entry<String, String>> iterator = models.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> entry = iterator.next();
            String model = entry.getKey();
            String url = entry.getValue();
            String finalCookie = TokenUtil.getFinalCookie(cookie2,cookie4,url);
            resultMap.put(model,finalCookie);
        }

        //处理新的

        String dothingsuiNewUrl = models_new.get(Constant.MODEL_DOTHINGSUI_NEW);
        String finalCookie = TokenUtil.getFinalCookieForNewThing(cookie2,cookie4,dothingsuiNewUrl,account,passwd);
        resultMap.put(Constant.MODEL_DOTHINGSUI_NEW,finalCookie);

        return resultMap;
    }

    private static String getFinalCookieForNewThing(String cookie2, String cookie4, String directurl,String account,String passwd) throws IOException {

        String newCookie = cookie4.split(";")[0] +";"+cookie2;
        //用于跳转的url
        // http://59.225.201.162:8086/work_table
        Map<String,String> result = WestarHttpUtil.getForAllMethod(directurl,newCookie,null);

        String trigger_sso_url = "http://59.225.201.162:8086/api/auth/jwt/trigger_sso_url";
        Map<String,String> trigger_sso_urlResult = WestarHttpUtil.getForAllMethod(trigger_sso_url,newCookie,null);
        String getResourceUrl = JSONObject.parseObject(trigger_sso_urlResult.get(RESPONEBODY.toString())).getString("data");

        Map<String,String> getResourceResult = WestarHttpUtil.getForAllMethod(decodeUrl(getResourceUrl),newCookie,null);

        String offLineUrl = Jsoup.parse(getResourceResult.get(RESPONEBODY.toString())).getElementById("offLine").val();
        String EXCHANGCookie = getResourceResult.get(COOKIE.toString());
        newCookie += EXCHANGCookie.split(";")[0] +";";
        Map<String,String> offLineResult = WestarHttpUtil.getForAllMethod(decodeUrl(offLineUrl),newCookie,null);

        //http://59.225.209.134:8080/open-platform-oauth/oauth/authorize
        String authorizeUrl = offLineResult.get(LOCATION.toString());
        Map<String,String> authorizeResult = WestarHttpUtil.getForAllMethod(decodeUrl(authorizeUrl),newCookie,null);

        String OAUTH2SESSION = authorizeResult.get(COOKIE.toString());
        newCookie += OAUTH2SESSION.split(";")[0] +";";
        String callbackUrl = authorizeResult.get(LOCATION.toString());


        Map<String,String> callbackResult = WestarHttpUtil.getForAllMethod(callbackUrl,newCookie,null);

        String ssoLoginUrl ="http://59.225.201.162:8086/api/auth/jwt/sso_login_url";
        Map<String,String> ssoLoginUrlResult = WestarHttpUtil.getForAllMethod(ssoLoginUrl,newCookie,null);

        String onlineauthorizeUrl = JSONObject.parseObject(ssoLoginUrlResult.get(RESPONEBODY.toString())).getString("data");
        Map<String,String> onlineauthorizeResult = WestarHttpUtil.getForAllMethod(decodeUrl(onlineauthorizeUrl), EXCHANGCookie+";"+OAUTH2SESSION,null);

        String newAuthUrl = onlineauthorizeResult.get(LOCATION.toString());
        Map<String,String> newAuthResult = WestarHttpUtil.getForAllMethod(decodeUrl(newAuthUrl),newCookie,null);

        Document docV2 = Jsoup.parse(newAuthResult.get(RESPONEBODY.toString()));
        Elements forms = docV2.select( "#loginForm");
        String action = forms.attr("action");

        Map<String,String> formData = new HashMap<>();
        Elements inputs = forms.select( "input");
        if(null!=inputs && !inputs.isEmpty()){
            for (Element input: inputs) {
                String name = input.attr( "name");
                String defvalue= input.attr( "value");
                if(StringUtils.isNotEmpty(  name)){
                    formData.put( name,defvalue );
                }

            }
            formData.put( "username",account );
            formData.put( "password",passwd );
        }

        Iterator<Map.Entry<String, String>> itor = formData.entrySet().iterator();

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for(int i=0;itor.hasNext();i++){
            Map.Entry<String, String> entry = itor.next();
            NameValuePair pair1 = new BasicNameValuePair(entry.getKey(),entry.getValue());
            pairs.add(pair1  );
        }


        DefaultHttpClient httpClient = null;
        HttpPost httpPost = null;
        String resultA = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost("https://"+ SysConst.DOMAIN+"" + action);
            httpPost.addHeader( "Cookie",newCookie);
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8) );
            HttpResponse response = httpClient.execute(httpPost);


            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    resultA = EntityUtils.toString(resEntity,"utf-8");
                    httpPost.releaseConnection();
                }else{
                    httpPost.releaseConnection();
                }
            }else{
                httpPost.releaseConnection();
            }
        }catch(IOException ex){
            ex.printStackTrace();
            if(null != httpPost){
                httpPost.releaseConnection();
            }
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            if(null != httpPost){
                httpPost.releaseConnection();
            }
        }

        newAuthResult = WestarHttpUtil.getForAllMethod(newAuthUrl,newCookie,null);
        newAuthResult.get(RESPONEBODY.toString());

        String location = newAuthResult.get(LOCATION.toString());
        newAuthResult = WestarHttpUtil.getForAllMethod(location,newCookie,null);

        while (newAuthResult.get(CODE.toString()).equalsIgnoreCase("302")){
            location = newAuthResult.get(LOCATION.toString());
            newAuthResult = WestarHttpUtil.getForAllMethod(location,newCookie,null);
            newAuthResult.get(RESPONEBODY.toString());
        }

        String url = "http://59.225.201.162:8086/api/auth/jwt/trigger_sso_url";
        newAuthResult = WestarHttpUtil.getForAllMethod(url,newCookie,null);

        url = JSONObject.parseObject(newAuthResult.get(RESPONEBODY.toString())).getString("data");
        newAuthResult = WestarHttpUtil.getForAllMethod(url,newCookie,null);

        url = Jsoup.parse(newAuthResult.get(RESPONEBODY.toString())).getElementById("offLine").val();
        newAuthResult = WestarHttpUtil.getForAllMethod(url,newCookie,null);

        String codeWithUrl = null;

        while (newAuthResult.get(CODE.toString()).equalsIgnoreCase("302")){
            location = newAuthResult.get(LOCATION.toString());
            if(location.indexOf("/auth/callback")>=0){
                URIBuilder uriBuilder = null;
                try {
                    uriBuilder = new URIBuilder(location);
                    List<NameValuePair> queryParams = uriBuilder.getQueryParams();
                    for (NameValuePair queryParam : queryParams) {
                        String name = queryParam.getName();
                        if(name.equalsIgnoreCase("code")){
                            String code = queryParam.getValue();

                            codeWithUrl = "http://59.225.201.162:8086/api/auth/jwt/egov_sso/"+code;
                        }
                    }
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                if(StringUtils.isNotEmpty(codeWithUrl)){
                    break;
                }
            }
            newAuthResult = WestarHttpUtil.getForAllMethod(location,newCookie,null);
            newAuthResult.get(RESPONEBODY.toString());
        }
        if(StringUtils.isNotEmpty(codeWithUrl)){

            newAuthResult = WestarHttpUtil.getForAllMethod(codeWithUrl,newCookie,null);
            return JSONObject.parseObject(newAuthResult.get(RESPONEBODY.toString())).getString("data");
        }else{
            return null;
        }

    }

    private static String decodeUrl(String url) throws UnsupportedEncodingException {
//        return url;
        return URLDecoder.decode(url,"UTF-8");
    }

    /**
     * 仅用于登录使用的https
     * @param url 登录链接
     * @param charset 字符集
     * @param cookie2 访问的cookie
     * @return
     * @throws Exception
     */
    private static String doHttpsPost(String url,String charset,String cookie2) throws MalformedURLException, SelfHttpException {
        String formData = new Uri(url).getQuery();

        formData = formData.substring( 1 );
        String[] aa = formData.split( "&" );
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (String a: aa) {
            a = a.replaceAll( "%2F","/" ).replaceAll( "%3A",":" );
            NameValuePair pair1 = new BasicNameValuePair(a.split( "=" )[0],a.split( "=" )[1]);
            pairs.add(pair1  );
        }

        try{
            DefaultHttpClient httpClient = null;
            HttpPost httpPost = null;
            String result = null;
            httpClient = new SSLClient();
            httpPost = new HttpPost( url);
            httpPost.addHeader( "Cookie",cookie2);
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8) );
            HttpResponse response = httpClient.execute(httpPost);

            int StatusCode = response.getStatusLine().getStatusCode();
            if(StatusCode == 302){
                String location = response.getLastHeader( "Location").getValue();
                return location;
            }else{
                throw new SelfHttpException(SelfHttpException.PAGE_RE_LOGIN ,"访问地址需要重新登录！","");
            }
        }catch(Exception ex){
            throw new SelfHttpException(SelfHttpException.UNKNOMN_ERROR ,"%s","访问地址https错误！");
        }
    }

    /**
     * 跳转登录揭秘那
     * @param charset 字符集
     * @param cookie2 访问的cookie
     * @return
     * @throws LoginException
     */
    private static String loginAction(String loginPageV2, String username, String password, String charset, String cookie2)
            throws SelfHttpException, IOException {
        String loginSwitchUrl = "https://"+SysConst.DOMAIN+"/auth/nationalPlatform/loginSwitch";
        Map<String, String> resultMap = WestarHttpUtil.getForAllMethod(loginSwitchUrl, cookie2, null);
//        Iterator<Map.Entry<String, String>> iterator = resultMap.entrySet().iterator();
//        while (iterator.hasNext()){
//            Map.Entry<String, String> entry = iterator.next();
//            System.out.println("loginSwitch --> key = " + entry.getKey());
//            System.out.println("loginSwitch --> value = " + entry.getValue());
//        }

        JSONObject jsonObject = JSONObject.parseObject(resultMap.get(RESPONEBODY.toString()));
        boolean OK = jsonObject.getBoolean("OK");

        Document docV2 = Jsoup.parse(loginPageV2);
        Elements forms = docV2.select( "#loginForm");
        String action = forms.attr("action");

        Map<String,String> formData = new HashMap<>();
        Elements inputs = forms.select( "input");
        if(null!=inputs && !inputs.isEmpty()){
            for (Element input: inputs) {
                String name = input.attr( "name");
                String defvalue= input.attr( "value");
                if(StringUtils.isNotEmpty(  name)){
                    formData.put( name,defvalue );
                }

            }
            formData.put( "username",username);
            formData.put( "password",password);
        }

        Iterator<Map.Entry<String, String>> itor = formData.entrySet().iterator();

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for(int i=0;itor.hasNext();i++){
            Map.Entry<String, String> entry = itor.next();
            NameValuePair pair1 = new BasicNameValuePair(entry.getKey(),entry.getValue());
            pairs.add(pair1  );
        }


        DefaultHttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost("https://"+ SysConst.DOMAIN+"" + action);
            httpPost.addHeader( "Cookie",cookie2);
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8) );
            HttpResponse response = httpClient.execute(httpPost);


            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                    httpPost.releaseConnection();
                }else{
                    httpPost.releaseConnection();
                    throw new SelfHttpException(SelfHttpException.PAGE_NOT_FOUND,"s%", "中间件获取响应实体为空，请联系管理人员！");
                }
            }else{
                httpPost.releaseConnection();
                throw new SelfHttpException( SelfHttpException.PAGE_NOT_FOUND,"s%", "中间件响应内容为空，请联系管理人员！");
            }
        }catch(IOException ex){
            ex.printStackTrace();
            if(null != httpPost){
                httpPost.releaseConnection();
            }
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            if(null != httpPost){
                httpPost.releaseConnection();
            }
            throw new SelfHttpException( SelfHttpException.PAGE_NOT_FOUND,"s%", "中间件https登录地址错误，请联系管理人员！");
        }
        return result;
    }

    /**
     *
     * @return
     * @throws IOException
     */
    private static String getAuthorizePage(String url) throws IOException, SelfHttpException {
        //系统入口
        String firtUrl = "http://"+ SysConst.DOMAIN+"/oauth2/login";
        if(null != url){
            firtUrl = url;
        }
        //初始化httpclient
        HttpClient httpclient = new HttpClient();
        //设置cookie策略
        httpclient.getParams().setCookiePolicy( CookiePolicy.BROWSER_COMPATIBILITY);
        //该方法为get请求
        HttpMethod method = new GetMethod();
        //设置访问路径
        method.setPath(firtUrl);

        //执行请求
        int code = httpclient.executeMethod(method);
        //访问结果
        if(code == 200){
            //获取响应页面
            String loginPage =  method.getResponseBodyAsString();
            //页面Doc化
            Document doc = Jsoup.parse(loginPage);
            //页面表单元素
            Elements eleForm = doc.select("form");
            //页面需要执行的请求
            String submitForm = eleForm.attr( "action");

            method.releaseConnection();
            return submitForm;
        }else{
            method.releaseConnection();
            throw new SelfHttpException(SelfHttpException.PAGE_NOT_FOUND,"中间件不能访问网络，请求不成功!" , "");
        }
    }

    /**
     * 解析Respone的cookie
     * @param method
     * @return
     */
    private static String getCookie(HttpMethod method) {
        String cookie = method.getResponseHeader( "Set-Cookie" ).getValue();

        String[] cookies = cookie.split( "," );

        String result = "";
        for (String cookieStr: cookies) {
            result = result + cookieStr.split( ";" )[0] + ";";
        }
        return result;
    }

}
